//
//  Track.m
//  citycar
//
//  Created by Tang JiaQi on 3/15/11.
//  Copyright 2011 HOME. All rights reserved.
//

#import "Track.h"
#import "Car.h"
#import "Coordinate.h"

@implementation Track

@synthesize m_pTrackCellList;
@synthesize m_pFocusCar;

-(id) init
{
	if((self == [super init]))
	{
		m_pTrackCellList = [[NSMutableArray alloc] init];
		[self schedule:@selector(UpdateTrack:)];
	}
	return self;
}

-(BOOL) AddTrackCell: (NSString*) cellName
{
	CCSprite* newTrackCell = [CCSprite spriteWithFile: cellName];
	if(newTrackCell == nil)
		return NO;
	[newTrackCell.texture setAliasTexParameters];
	[m_pTrackCellList addObject: newTrackCell];
	[self addChild: newTrackCell];
	return YES;
}

-(void) SetFocusCar: (Car*)pCar
{
	m_pFocusCar = pCar;
}

-(void) Reset
{	
	CCSprite* pCellOne	= [m_pTrackCellList objectAtIndex: 0];
	CCSprite* pCellTwo	= [m_pTrackCellList objectAtIndex: 1];
	
	CGSize winSize = [[CCDirector sharedDirector] winSize];
	pCellOne.position = ccp(winSize.width / 2.f, winSize.height / 2.f);
	pCellTwo.position = ccp(winSize.width / 2.f, winSize.height * 3.f / 2.f);
}

-(void) UpdateTrack: (ccTime)dt
{
	CGSize winSize = [[CCDirector sharedDirector] winSize];
	CGFloat fixedX = winSize.width / 2.f;
	for (int i = 0; i < 2; ++i) {
		CCSprite* pCell	= [m_pTrackCellList objectAtIndex: i];
		CGPoint realworldPt = [Coordinate screenToRealWorld: pCell.position];
		CGFloat cellOneY = realworldPt.y;
		float moveSpeed = 0.f;
		if(m_pFocusCar)
		{
			moveSpeed = m_pFocusCar.velocity.y;
		}
		cellOneY -= moveSpeed * dt;
		cellOneY = [Coordinate realWorldToScreen:ccp(realworldPt.x, cellOneY)].y;
		if(cellOneY <= -winSize.height / 2.f)
		{
			CGFloat remaining = cellOneY - (-winSize.height / 2.f);
			cellOneY = winSize.height * 3.f / 2.f - 2.f + remaining;
		}
		pCell.position = ccp(fixedX, cellOneY);
	}
}

@end
